package cn.tedu.charging.order.webSocket;

import cn.tedu.charging.common.protocol.WebSocketMessage;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
@ServerEndpoint("/ws/server/{userId}")
public class WebSocketServer {
    public void pushMessage(Integer userId,String message){
        Session session=USERS.get(userId);
        if(session!=null){
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.info("消息发送失败,原因:{}", e.getMessage());
            }
        }else {
            // todo 发送到消息队列
            log.info("拿不到该用户连接");
        }
    }
    private static Map<Integer,Session>USERS=new ConcurrentHashMap<>();
    @OnOpen
    public void OnOpen(Session session,@PathParam("userId")Integer userId){
        log.info("客户端创建链接");
        log.info("sessionId:{}",session.getId());
        log.info("建立链接的用户:{}",userId);
        USERS.put(userId,session);
    }

    @OnClose
    public void OnClose(Session session,@PathParam("userId")Integer userId){
        log.info("客户端关闭链接");
        log.info("sessionId:{}",session.getId());
        USERS.remove(userId);
    }

    @OnError
    public void OnError(Session session,Throwable e){
        log.info("客户端链接出现异常:{}", e.getMessage());
        log.info("sessionId:{}",session.getId());
    }

    @OnMessage
    public void OnMessage(Session session,String message) throws IOException {
        log.info("客户端发送的消息为：{}",message);
        log.info("消息来自于session:{}", session.getId());
        WebSocketMessage webSocketMessage = new WebSocketMessage();
        webSocketMessage.setState(4);
        webSocketMessage.setMessage("你好我是服务端");
        webSocketMessage.setData(null);
        session.getBasicRemote().sendText(JSON.toJSONString(webSocketMessage));
    }
}
